package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.management.aop.anno.ReportRedisAnno;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;


/**
 * @文件名: ReportRedisAspct
 * @作者: DX
 * @创建日期: 2025/10/17
 * @描述:
 */
@Slf4j
@Aspect
@Component
public class ReportRedisAspct {

    @Autowired
    private StringRedisTemplate redisClient;

    @Pointcut("@annotation(com.qk.management.aop.anno.ReportRedisAnno)")
    public void pt(){}

    @Around("pt()")
    public Object reportRedis(ProceedingJoinPoint pjp){

        Object proceed = null;
        String redisKey = null;
        TimeUnit expireTimeUnit = null;
        long exPireTime = 0L;

        try {
            String name = pjp.getSignature().getName();

            Method method = pjp.getTarget().getClass().getMethod(name);

            ReportRedisAnno annotation = method.getAnnotation(ReportRedisAnno.class);

            redisKey = annotation.keyPrefix()+name;

            exPireTime = annotation.exPireTime();

            expireTimeUnit = annotation.expireTimeUnit();


            String jsonStr =  redisClient.opsForValue().get(redisKey);

            if (ObjectUtil.isNotNull(jsonStr)) {
                proceed = JSONUtil.toBean(jsonStr, method.getReturnType());
                log.info("缓存命中，key: {}", redisKey);
                return proceed;
            } else {
                log.info("缓存未命中，key: {}", redisKey);
            }
        } catch (Exception e) {
            log.error("redis缓存异常{}", e.getMessage());
        }

        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            log.error("查询异常{}", e.getMessage());
            CommonException.thowsCommonException(ParamEnum.OPERATE_ERROR);
        }


            try {
                redisClient.opsForValue().set(redisKey, JSONUtil.toJsonStr(proceed), exPireTime, expireTimeUnit);
                log.info("数据已写入缓存，key: {}", redisKey);
            } catch (Exception e) {
                log.error("redis缓存异常{}", e.getMessage());
            }

        return proceed;

    }
}